package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"math"
	"os"
	"time"
)

//日志中间件logrus
func Logger() gin.HandlerFunc  {
	filePath := "runtime/api/"//日志路径
	linkName := "lasted" //设置软链接
	scr, err := os.OpenFile(filePath, os.O_RDWR | os.O_CREATE, 0755)
	if err != nil {
		fmt.Println("err:" , err)
	}
	logger := logrus.New()

	logger.Out = scr

	logger.SetLevel(logrus.DebugLevel)

	fileName := filePath + "%Y%m%d.log"
	logWriter, _ := rotatelogs.New(fileName,
		rotatelogs.WithMaxAge(7 * 24 * time.Hour),//保存最大时间 7天
		rotatelogs.WithRotationTime(24 * time.Hour),//多久分割一次 24小时
		rotatelogs.WithLinkName(linkName),//设置根目录的软链接名称
	)

	writeMap := lfshook.WriterMap{
		logrus.InfoLevel: logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
		logrus.WarnLevel: logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.PanicLevel: logWriter,
	}

	hook := lfshook.NewHook(writeMap, &logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	logger.AddHook(hook)

	return func(c *gin.Context) {
		startTime := time.Now()
		c.Next()
		stopTime := time.Since(startTime)

		spendTime := fmt.Sprintf("%d ms", int(math.Ceil(float64(stopTime.Nanoseconds()/1000000.0))))
		hostName, err := os.Hostname()
		if err != nil {
			hostName = "unknown"
		}
		statusCode := c.Writer.Status()
		clientIp := c.ClientIP()
		userAgent := c.Request.UserAgent()
		dataSize := c.Writer.Size()
		method := c.Request.Method
		path := c.Request.RequestURI
		entry := logger.WithFields(logrus.Fields{
			"HostName" : hostName,
			"SpendTime" : spendTime,
			"StatusCode" : statusCode,
			"ClientIp" : clientIp,
			"UserAgent" : userAgent,
			"DataSize" : dataSize,
			"Method" : method,
			"Path" : path,
		})
		if len(c.Errors) > 0 {
			//系统内部错误
			entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
		}
		if statusCode == 500 {
			entry.Error()
		}else if statusCode >= 400 {
			entry.Warn()
		}else {
			entry.Info()
		}


	}
}


